var SiteMap = SiteMap || {};

// Research Content is presented by One Spreadsheet 
// Which loads both: Sub Menu and Document Content &
// creates anchor links and accordion navigation
// to jump between sections
SiteMap.Research = {
	Folder: {
		id: '0Bxm7KG10dy1ZOVpUTVZWbFhoSTQ',
		title: 'Research',
		spreadsheet: '1md7tduUs2HtgOfXF1NuYUnjUbtn2bNbpi2-b0A58vaE',
		script: 'https://script.google.com/a/macros/google.com/s/AKfycbw3v29pzqiZB7CcVkByZ7yR6m3wi_NBJ1sHiLhkoejfM9UWRGI3/exec'
	}
};

SiteMap.Research.Router = {	
	init: function() {	
		hasher.changed.add(SiteMap.Research.Router.handle);
		hasher.initialized.add(SiteMap.Research.Router.handle);
		hasher.init();
	},
	
	handle: function(newHash, oldHash) {			
		if (newHash == undefined || newHash == "") {			
			SiteMap.Research.SubPage.init();
		} else if (newHash != oldHash) {
			if (SiteMap.Research.SubPage.isLoaded) {				
				SiteMap.Research.SubPage.scrollTo(newHash);
			} else {
				SiteMap.Research.SubPage.init(newHash);
			}
		}	
	}
};

SiteMap.Research.SubPage = {
	speed:  0.200,
	anchor: null,
	isLoaded: false,
	
	init: function(newHash) {
		this.anchor = (newHash != undefined) ? newHash : null;	
		if (!this.isLoaded.page) {
			this.elmLoader     = $('#loader');
			this.elmTitle      = $('#subpage-title');
			this.elmMenu       = $('#subpage-menu');
			this.elmContent    = $('#subpage-content');
			this.elmDocument   = $('#document');
			
			this.observe();	
			this.getSpreadsheet();
		}
	},
	
	observe: function() {
		$(this.elmContent).on('contentLoaded', function(e) {
			SiteMap.Research.SubPage.isLoaded = true;
			SiteMap.Research.SubPage.display();
			SiteMap.Research.SubPage.observeMenu();
			if (SiteMap.Research.SubPage.anchor) {
				SiteMap.Research.SubPage.scrollTo(SiteMap.Research.SubPage.anchor);
			}
		});
		
		// makes sub-menu stay in view on scroll
		$(window).scroll(function(){
			if ($(window).scrollTop() > 56) {
				$('#subpage-menu').addClass('floating');
			} else {
				$('#subpage-menu').removeClass('floating');
			}
		});
	},
	
	// accordion and anchor programming
	observeMenu: function() {
		$('#subpage-menu > ul > li > span').click(function(e) { 
			e.preventDefault();
			var anchor = $(this).parent().attr('data-scroll');

			$('#subpage-menu li').removeClass('active');
			$(this).closest('li').addClass('active');	
			var checkElement = $(this).next();
			if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
				$(this).closest('li').removeClass('active');
				checkElement.slideUp('normal');
			}
			if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
				$('#subpage-menu ul ul:visible').slideUp('normal');
				checkElement.slideDown('normal');
				hasher.setHash(anchor);
			}
			if($(this).closest('li').find('ul').children().length == 0) {
				return true;
			} else {
				return false;	
			}		
		});
		
		$('#subpage-menu li.has-sub ul > li > span').fastClick(function(e){
			var parent = $(this).parent(),
				anchor = $(this).parent().attr('data-scroll');
			
			$(parent).siblings().removeClass('active');
			$(parent).addClass('active');
			hasher.setHash(anchor);
		});
		
	},
	
	scrollTo: function(anchor) {
		if (!anchor || anchor == undefined) { 
			return; 
		} else { 
			this.anchor = anchor; 
		}
		
		$('html, body').animate({
			scrollTop: $('#' + anchor).offset().top - 160 // minus height of top header
		});	
	},
	
	getSpreadsheet: function() {
		TweenMax.to($(this.elmContent), this.speed/2, { opacity: 0, ease: Sine.easeInOut, onComplete: function(){
			$(this).css('display','none');
		} });
		
		var URL = SiteMap.Research.Folder.script + "?ss="+ SiteMap.Research.Folder.spreadsheet + "&prefix=SiteMap.Research.SubPage.loadSpreadsheet";		
		$.ajax({ url: URL, dataType: 'jsonp' });
	},
	
	// this defines how the content that comes back from apps script
	// will be presented on the web
	loadSpreadsheet: function(dataSheets) {	
		var contentHTML = '',
			menuHTML    = '', 
			menuArray   = [], 
			k           = -1,
			monthNames  = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]
		;
		
		for (var i = 0, len = dataSheets.length; i < len; i++) {
			var dataLinks = dataSheets[i].data;	
			for (var j = 0, len2 = dataLinks.length; j < len2; j++) {
				var item = dataLinks[j];
				
				if (item[0] !== "") { // top level title
					menuArray[++k] = { id: 'anchor'+i+"-"+j, title: item[0], subs: [] };
					contentHTML += '<h2 id="anchor'+i+"-"+ j+'">' + item[0] + '</h2>';
				}				
				
				if (item[1] !== "") {
					menuArray[k].subs.push({ id: 'subanchor'+i+'-'+j, title: item[1] });
					contentHTML += '<h3 id="subanchor'+i+"-"+j+'">' + item[1] + '</h3>';
				}
				
				contentHTML += '<h4>';	
				if (item[3] !== "") { // link wrap					
					contentHTML += '<a href="'+item[3]+'">' + item[2] + '</a>';
				}
				
				if (item[4] !== "") {
					var date = new Date(item[4]);
					contentHTML += '<br><span class="date">' + monthNames[date.getMonth()] + ' ' + date.getFullYear() + '</span>'; 
				}
				
				if (item[5] !== "") {
					contentHTML += ' | <span class="researcher">' + item[5] + '</span>'; 
				}	
				
				contentHTML += '</h4>';	
				
				if (item[6] != undefined || item[6] !== "") {
					contentHTML += '<p>'+ item[6] + '</p>';
				}
			}		
		}
		
		menuHTML = this.buildMenu(menuArray);		
		$(this.elmTitle).html(SiteMap.Research.Folder.title);
		$(this.elmMenu).html(menuHTML);
		$(this.elmDocument).html(contentHTML);
		$(this.elmContent).trigger('contentLoaded');
	},
	
	// menu gets displaed as accordion with anchor links
	buildMenu: function(menuArray){
		var menuHTML = '<ul class="docmenu" id="docmenu">';		
		for (var i = 0, len = menuArray.length; i < len; i++) {
			menuHTML += '<li class="has-sub" data-scroll="'+menuArray[i].id+'"><span>' + menuArray[i].title + '</span>'; // <a href="#'+menuArray[i].id+'"></a>
			menuHTML += '<ul style="display:none;">';
			for (var j = 0, len2 = menuArray[i].subs.length; j < len2; j++) {
				menuHTML += '<li data-scroll="'+menuArray[i].subs[j].id+'"><span>' + menuArray[i].subs[j].title + '</span></li>'; // <a href="#'+menuArray[i].subs[j].id+'"></a>
			}
			menuHTML += '</ul>';
			menuHTML += '</li>';
		}
		
		menuHTML += '</ul>';
		return menuHTML;
	},
	
	// append document loader
	appendLoader: function() {
		console.log('appending loader >>>');
		var html = '<div class="subpage-loader" id="subpage-loader"><div class="content"><article><img src="../img/general/loader-subpage.gif" width="32" height="32" alt="Loading..."></article></div></div>';
		$(this.elmContent).parent().append(html);
	},
	
	// remove document loader
	removeLoader: function() {
		console.log('removing loader >>>');
		
		if ($('#loader')) {
			TweenMax.to($('#loader'), this.speed, { opacity: 0, onComplete: function(){
				$('#loader').remove();
			} });
		}
		
		if ($('#subpage-loader')) {
			TweenMax.to($('#subpage-loader'), this.speed, { opacity: 0, onComplete: function(){
				$('#subpage-loader').remove();
			} });
		}	
	},
	
	// display all content simultaneously
	display: function() {
		$(this.elmMenu).css('display','block');
		$(this.elmContent).css('display','block');				
		TweenMax.to([$(this.elmMenu), $(this.elmContent)], this.speed, { opacity: 1, ease: Sine.easeInOut, onComplete: function() {
			SiteMap.Research.SubPage.removeLoader();
		} });
	}
};


$(document).ready(function(){
	SiteMap.Research.Router.init();	
});
